#!/usr/bin/env node

const WebSocket = require('ws');

console.log('=== 专门测试聊天功能 ===\n');

function testChatFunction() {
  const wsUrl = 'wss://c4pad.fun/socket.io/?EIO=4&transport=websocket';
  console.log('连接到:', wsUrl);
  
  const ws = new WebSocket(wsUrl);
  let isConnected = false;
  let hasJoinedChat = false;
  
  ws.on('open', function open() {
    console.log('✅ WebSocket连接成功');
    
    // 立即发送握手
    ws.send('40');
  });
  
  ws.on('message', function message(data) {
    const msg = data.toString();
    console.log('📨 收到:', msg);
    
    if (msg.startsWith('40') && !isConnected) {
      console.log('✅ Socket.IO握手成功');
      isConnected = true;
      
      // 等待1秒后加入聊天
      setTimeout(() => {
        if (!hasJoinedChat) {
          console.log('🔄 尝试加入聊天...');
          const username = 'TestUser' + Date.now();
          const joinMsg = JSON.stringify(['join_chat', { username }]);
          console.log('发送消息:', '42' + joinMsg);
          ws.send('42' + joinMsg);
          hasJoinedChat = true;
          
          // 等待3秒后发送聊天消息
          setTimeout(() => {
            console.log('💬 发送聊天消息...');
            const chatMsg = JSON.stringify(['send_message', { message: 'Hello from test!' }]);
            ws.send('42' + chatMsg);
          }, 3000);
        }
      }, 1000);
    }
    
    if (msg.startsWith('42')) {
      try {
        const eventData = JSON.parse(msg.substring(2));
        console.log('📢 事件:', eventData[0]);
        console.log('📄 数据:', JSON.stringify(eventData[1], null, 2));
      } catch (e) {
        console.log('❌ 无法解析事件:', e.message);
      }
    }
    
    if (msg === '3') {
      console.log('💓 心跳');
      ws.send('2'); // 回应心跳
    }
  });
  
  ws.on('error', function error(err) {
    console.error('❌ 错误:', err.message);
  });
  
  ws.on('close', function close(code, reason) {
    console.log('🔌 连接关闭');
    console.log('代码:', code);
    console.log('原因:', reason ? reason.toString() : '无');
  });
  
  // 10秒后关闭
  setTimeout(() => {
    console.log('⏰ 测试结束，关闭连接');
    ws.close();
  }, 10000);
}

testChatFunction();
